#include "head.h"

#define FIFO_NAME "./fifo_test"

int main(int argc, char const *argv[])
{
    mkfifo( FIFO_NAME, 0777 );

    int FifoFd;
    FifoFd = open( FIFO_NAME, O_RDONLY );
    if ( -1 == FifoFd )
    {
        perror( "fail open fifo" );
        return -1;
    }

    
    int Flag;
    Flag = fcntl( 0, F_GETFL );    // 1. 获取 stdin (0) 的文件描述符原属性
    Flag |= O_NONBLOCK;            // 2. 在原属性上添加 非阻塞属性
    fcntl( 0, F_SETFL, Flag );     // 3. 设置 stdin 的新属性

    Flag = fcntl( FifoFd, F_GETFL );    // 1. 获取 FifoFd 的文件描述符原属性
    Flag |= O_NONBLOCK;                 // 2. 在原属性上添加 非阻塞属性
    fcntl( FifoFd, F_SETFL, Flag );     // 3. 设置 FifoFd 的新属性

    int i;

    for( i = 1; i <= 100; ++i ) 
    {
        char strBuff[1024] = {0};
        ssize_t Ret;
        Ret = read( 0, strBuff, sizeof(strBuff) );
        if ( -1 == Ret )
        {
            perror( "fail read stdin" );
            return -1;
        }
        if( Ret > 0)
        {
            printf( "Conter %3d --- Recvfrom stdin #%ld bytes : %s\n", i, Ret, strBuff );
        }

        memset( strBuff, 0, sizeof(strBuff) );
        Ret = read( FifoFd, strBuff, sizeof(strBuff) );
        if ( -1 == Ret )
        {
            perror( "fail read fifo" );
            return -1;
        }
        if ( Ret > 0 )
        {
            printf( "Conter %3d --- Recvfrom FIFO: %s\n", i, strBuff );
        }

    }

    close( FifoFd );

    return 0;
}
